<?php namespace Admin\Model;
use Hdphp\Model\Model;
class Category extends Model{
	protected $table = "category";
	//验证
	protected $validate = array(
		array('cname','required','名称不能为空',3,3),
		array('cname','maxlen:30','内容不能超过30个字符',3,3),
		array('csort','num:0,65535','数字超出范围',3,3)
	);
	//添加
	public function store(){
		//触发自动验证
		if(!$this->create()) return false;
		//添加并返回
		return $this->add();
	}
	//删除
	public function del($cid){
		$pid = $this->where("cid={$cid}")->pluck('pid');
		$this->where("pid={$cid}")->save(array('pid'=>$pid));
		$this->delete($cid);
		return true;
	}
	//编辑
	public function edit(){
		if($this->create()){
			$this->save();
		return true;
		}
		 return false;
	}
	//获取除自己以外的其他分类
	public function others($cid){
		//获取子集的ID
		$cids = $this->getSon($this->get(),$cid);
		$cids[]=$cid;
		$data = $this->where("cid NOT IN (". implode(',',$cids).") ")->get();
		return Data::tree($data,'cname');
	}
	//根据分类筛选商品
    public function cidGetGid($cid){
        //调取当前分类的所有子分类
        $cids = $this->getSon(Db::table('category')->get(),$cid);
        $cids[] = $cid;
        //通过分类id获得商品id
        $gids = Db::table('goods')->where("category_cid in(" . implode(',', $cids) . ")")->lists('gid');
        return $gids;
    }

	//获得子集
	public function getSon($data,$cid){
		$temp = array();  //定义静态变量，保存所有获得的子集
		foreach ($data as $v) {
				//如果找到子集
			if($cid == $v['pid']){
				$temp[]=$v['cid'];
				$temp = array_merge($temp,$this->getSon($data,$v['cid']));
			}
		}
		return $temp; //返回所有遍历出来的cid
	}






}
?>